from apps.contents.models import GoodsChannel, ContentCategory, GoodsCategory
from django.template import loader
from django.conf import settings
import os


def static_index():
    goods_dict = {}

    # 取出11个分组的结果集
    groups = GoodsChannel.objects.all().order_by('group_id', 'sequence')

    # 遍历获取每个组的对象
    for group in groups:
        # 每个组的ID
        group_id = group.group_id

        if not group_id in goods_dict:
            goods_dict[group_id] = {'channels': [], 'sub_cats': []}

        classfly1 = group.category
        goods_dict[group_id]['channels'].append({
            'id': group.id,
            'name': classfly1.name,
            'url': group.url
        })

        for classfly2_conn in classfly1.subs.all():
            classfly2_list = []

            # classfly3 = classfly2_conn.subs.all()
            for classfly3_conn in classfly2_conn.subs.all():
                classfly2_list.append({
                    'id': classfly3_conn.id,
                    'name': classfly3_conn.name,
                })

            goods_dict[group_id]['sub_cats'].append({

                'id': classfly2_conn.id,
                'name': classfly2_conn.name,
                'sub_cats': classfly2_list
            })

        # # 取出二级分类的结果集
        # classfly2s = GoodsCategory.objects.filter(parent=classfly1s)
        #
        # for classfly2 in classfly2s:
        #
        #     classfly3s = GoodsCategory.objects.filter(parent=classfly2)
        #     classfly2_list = []
        #     for classfly3 in classfly3s:
        #         classfly2_list.append({
        #             'id': classfly3.id,
        #             'name': classfly3.name,
        #         })
        #
        #     goods_dict[group_id]['sub_cats'].append({
        #
        #         'id': classfly2.id,
        #         'name': classfly2.name,
        #         'sub_cats': classfly2_list
        #     })
        # 查询首页广告数据
    contents = {}
    # 先查询所有的广告种类，并遍历出每一种广告
    content_categories = ContentCategory.objects.all()
    for content_cat in content_categories:
        # 在遍历的过程中，取出每一种广告关联的广告内容
        # 一查多语法: 一方模型对象.一查多关联字段
        contents[content_cat.key] = content_cat.content_set.filter(status=True).order_by('sequence')

    context = {
        'categories': goods_dict,
        'contents': contents

    }

    temp = loader.get_template('index.html')
    html_txt = temp.render(context)
    path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')
    with open(path, 'w', encoding='utf-8') as f:
        f.write(html_txt)
